<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="goodsName">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品类别" prop="categoryId">
        <el-select v-model="queryParams.categoryId" placeholder="请选择商品类别" clearable>
          <el-option
            v-for="item in categoryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in statusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:stock:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="refreshData"
        >刷新</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="stockList"
      stripe
      border
    >
      <el-table-column label="商品ID" align="center" prop="goodsId" />
      <el-table-column label="商品编码" align="center" prop="goodsCode" />
      <el-table-column label="商品名称" align="center" prop="goodsName" min-width="150" />
      <el-table-column label="商品规格" align="center" prop="goodsSpec" />
      <el-table-column label="商品单位" align="center" prop="goodsUnit" />
      <el-table-column label="类别" align="center" prop="categoryName" />
      <el-table-column label="当前库存" align="center" prop="currentStock" />
      <el-table-column label="可用库存" align="center" prop="availableStock" />
      <el-table-column label="锁定库存" align="center" prop="lockedStock" />
      <el-table-column label="最低库存" align="center" prop="minStock" />
      <el-table-column label="最高库存" align="center" prop="maxStock" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
            {{ scope.row.status === '0' ? '正常' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listStock, exportStock } from '@/api/inventory/stock'

export default {
  name: 'InventoryDetails',
  data() {
    return {
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      // 库存列表
      stockList: [],
      // 显示搜索条件
      showSearch: true,
      // 类别选项
      categoryOptions: [],
      // 状态选项
      statusOptions: [
        { value: '0', label: '正常' },
        { value: '1', label: '停用' }
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsName: undefined,
        categoryId: undefined,
        status: undefined
      }
    }
  },
  created() {
    // 加载类别选项（这里可以从数据字典加载）
    this.loadCategoryOptions();
    // 获取库存列表
    this.getList();
  },
  methods: {
    // 加载类别选项
    loadCategoryOptions() {
      // 这里可以调用获取类别列表的API
      // 暂时使用静态数据
      this.categoryOptions = [
        { value: 1, label: '电子产品' },
        { value: 2, label: '办公用品' },
        { value: 3, label: '家居用品' }
      ];
    },
    // 获取库存列表
    getList() {
      this.loading = true;
      // 记录开始时间
      const startTime = new Date().getTime();
      
      // 使用原生fetch替代this.$http或封装的API调用，以便直接观察返回结果
      const token = this.$store.getters.token;
      const url = process.env.VUE_APP_BASE_API + '/system/stockinfo/list';
      const params = new URLSearchParams({
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize
      });
      
      if (this.queryParams.goodsName) {
        params.append('goodsName', this.queryParams.goodsName);
      }
      
      if (this.queryParams.categoryId) {
        params.append('categoryId', this.queryParams.categoryId);
      }
      
      if (this.queryParams.status) {
        params.append('status', this.queryParams.status);
      }
      
      // 打印请求详情，便于调试
      console.log('请求URL:', url);
      console.log('请求参数:', Object.fromEntries(params));
      
      fetch(`${url}?${params}`, {
        method: 'GET',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ' + token
        }
      })
      .then(response => {
        const endTime = new Date().getTime();
        console.log(`请求耗时: ${endTime - startTime}ms`);
        console.log('响应状态:', response.status, response.statusText);
        
        // 检查响应状态
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
      })
      .then(data => {
        console.log('获取到数据:', data);
        
        if (data.code === 200) {
          this.stockList = data.rows || [];
          this.total = data.total || 0;
        } else {
          this.$message.error(data.msg || '获取库存数据失败');
          this.stockList = [];
          this.total = 0;
        }
      })
      .catch(error => {
        console.error('获取库存列表失败:', error);
        this.$message.error('获取库存列表失败，请刷新页面重试');
        this.stockList = [];
        this.total = 0;
      })
      .finally(() => {
        this.loading = false;
      });
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置按钮操作
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 刷新数据
    refreshData() {
      this.getList();
    },
    // 导出按钮操作
    handleExport() {
      const queryParams = { ...this.queryParams };
      this.$confirm('是否确认导出所有库存数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$modal.loading("正在导出数据，请稍候...");
        exportStock(queryParams).then(response => {
          this.$modal.closeLoading();
          try {
            // 安全获取文件名
            let filename = '库存信息数据.xlsx';
            const disposition = response.headers && response.headers['content-disposition'];
            if (disposition) {
              const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
              const matches = filenameRegex.exec(disposition);
              if (matches != null && matches[1]) {
                filename = matches[1].replace(/['"]/g, '');
              }
            }
            
            // 检查响应数据是否存在
            if (!response.data) {
              throw new Error('响应数据为空');
            }
            
            // 创建Blob对象并下载
            const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' });
            const link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = filename;
            link.click();
            window.URL.revokeObjectURL(link.href);
            this.$modal.msgSuccess("导出成功");
          } catch (error) {
            console.error('处理导出响应时出错:', error);
            this.$modal.msgError("文件处理失败: " + (error.message || '未知错误'));
          }
        }).catch(err => {
          this.$modal.closeLoading();
          // 尝试解析错误响应
          let errorMsg = err.message || '未知错误';
          if (err.response && err.response.data) {
            try {
              // 尝试解析错误响应中的二进制数据为JSON
              const reader = new FileReader();
              reader.onload = e => {
                try {
                  const jsonObj = JSON.parse(e.target.result);
                  errorMsg = jsonObj.msg || jsonObj.message || errorMsg;
                  this.$modal.msgError("导出失败：" + errorMsg);
                } catch (parseError) {
                  this.$modal.msgError("导出失败：" + errorMsg);
                }
              };
              reader.readAsText(new Blob([err.response.data]));
            } catch (parseError) {
              this.$modal.msgError("导出失败：" + errorMsg);
            }
          } else {
            this.$modal.msgError("导出失败：" + errorMsg);
          }
        });
      }).catch(() => {
        // 用户取消导出
      });
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.search-box {
  margin-bottom: 20px;
}
.el-table {
  margin-top: 15px;
}
.mb8 {
  margin-bottom: 8px;
}
</style>